package com.hb.gp.util.tools;

public class GP_Tools {
	/**
	 * format command messages data 's length(lc)
	 * 
	 * @param data
	 * @return
	 */
	public static String getHexLength(String data) {
		if (data.length() % 2 != 0)
			data += " ";
		String l = Integer.toHexString(data.length() / 2);
		if (l.length() % 2 != 0) {
			l = 0 + l;
		}
		return l.toUpperCase();
	}

	/**
	 * the apdu with 84 's mac
	 * 
	 * @param apdu
	 * @param macKey
	 * @param lastMac
	 * @return
	 */
	public static String getApduMac(String apdu, String macKey, String lastMac) {
		// TODO Auto-generated method stub
		apdu = apdu.replace(" ", "");
		String CLA = apdu.substring(0, 2);
		String INS = apdu.substring(2, 4);
		String p1 = apdu.substring(4, 6);
		String p2 = apdu.substring(6, 8);
		String lc = apdu.substring(8, 10);
		String value = apdu.substring(10);
		// lc = Integer.toHexString(Integer.parseInt(lc, 16) + 8);
		lc = Integer.toHexString(value.length() / 2 + 8);
		if (lc.length() == 1) {
			lc = 0 + lc;
		}
		apdu = CLA + INS + p1 + p2 + lc + value;
		System.out.println("mac=" + lastMac + ",key=" + macKey + ",apdu="
				+ apdu);
		String mac = GP_GetMac.getIMac(apdu, macKey, lastMac, true);
		return (apdu + mac).toUpperCase();
	}

	/**
	 * the apdu with 84 's mac
	 * 
	 * @param apdu
	 * @param macKey
	 * @param lastMac
	 * @return
	 */
	public static String getApdu4Mac(String apdu, String macKey, String lastMac) {
		// TODO Auto-generated method stub
		apdu = apdu.replace(" ", "");
		String CLA = apdu.substring(0, 2);
		String INS = apdu.substring(2, 4);
		String p1 = apdu.substring(4, 6);
		String p2 = apdu.substring(6, 8);
		String lc = apdu.substring(8, 10);
		String value = apdu.substring(10);
		// lc = Integer.toHexString(Integer.parseInt(lc, 16) + 8);
		lc = Integer.toHexString(value.length() / 2 + 4);
		if (lc.length() == 1) {
			lc = 0 + lc;
		}
		apdu = CLA + INS + p1 + p2 + lc + value;
		System.out.println("mac=" + lastMac + ",key=" + macKey + ",apdu="
				+ apdu);
		String mac = GP_GetMac.getIMac(apdu, macKey, lastMac, true);
		return (apdu + mac.substring(0,8)).toUpperCase();
	}
}
